package com.hsgene.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.http.HttpConnectionManager;
import com.hsgene.common.util.sign.PayDigestUtil;
import com.hsgene.order.service.UserAuthenticationService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户身份验证impl
 *
 * @author wxf
 * @date 2018/10/26 14:26
 **/
@Service
public class UserAuthenticationServiceImpl implements UserAuthenticationService {
    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(UserAuthenticationServiceImpl.class);

    @Resource
    private HttpConnectionManager connectionManager;

    @Value("${jinll.verify.auth.url}")
    private String url;
    @Value("${jinll.access_key}")
    private String accessKey;
    @Value("${jinll.secret_key}")
    private String secretKey;

    /**
     * 校验用户身份
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> userAuthVerify(String userId) {
        try {
            //TODO
            //待优化
            StringBuilder builder = new StringBuilder();
            String andStr = CharactersConstant.AND;
            builder.append("access_key=").append(accessKey).append(andStr).append("timestamp=").append(System
                    .currentTimeMillis()).append(andStr).append("id=").append(userId);
            StringBuilder signBuilder = new StringBuilder();
            signBuilder.append(builder).append(andStr).append("secret_key=").append(secretKey);
            String sign = PayDigestUtil.md5(signBuilder.toString(), CharactersConstant.UTF_8).toUpperCase();
            builder.append(andStr).append("sign=").append(sign);
            String result = connectionManager.doGet(url + "?" + builder.toString(), CharactersConstant.UTF_8);
            JSONObject jsonObject = JSONObject.parseObject(result);
            return (Map<String, Object>) jsonObject.get("data");
        } catch (Exception e) {
            LOGGER.error("verify doctor auth is error...", e);
            return null;
        }
    }

}
